package com.first.xiinn.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import com.first.core.common.QueryFilter;
import com.first.core.web.action.BaseAction;
import com.first.xiinn.model.BookCatalog;
import com.first.xiinn.model.BookManager;
import com.first.xiinn.model.BookType;
import com.first.xiinn.model.User;
import com.first.xiinn.service.BookCatalogService;
import com.first.xiinn.service.BookService;
import com.first.xiinn.service.BookTypeService;
import com.first.xiinn.service.UserService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class BookAction extends BaseAction {
	@Resource
	private BookService bookService;
	@Resource
	private BookCatalogService catalogService;
	@Resource
	private UserService userService;
	@Resource
	private BookTypeService bookTypeService;
	private BookManager book;
	private String id;
	private String ids;
	private File filePto;
	private String filePtoFileName;
	private File fileElectronic;
	private String fileElectronicFileName;
	private String bookid;

	public String getBookid() {
		return bookid;
	}

	public void setBookid(String bookid) {
		this.bookid = bookid;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public BookManager getBook() {
		return book;
	}

	public void setBook(BookManager book) {
		this.book = book;
	}

	public File getFilePto() {
		return filePto;
	}

	public void setFilePto(File filePto) {
		this.filePto = filePto;
	}

	public String getFilePtoFileName() {
		return filePtoFileName;
	}

	public void setFilePtoFileName(String filePtoFileName) {
		this.filePtoFileName = filePtoFileName;
	}

	public File getFileElectronic() {
		return fileElectronic;
	}

	public void setFileElectronic(File fileElectronic) {
		this.fileElectronic = fileElectronic;
	}

	public String getFileElectronicFileName() {
		return fileElectronicFileName;
	}

	public void setFileElectronicFileName(String fileElectronicFileName) {
		this.fileElectronicFileName = fileElectronicFileName;
	}

	public static String getUserMenuDoc() {
		return USER_MENU_DOC;
	}

	private static final String USER_MENU_DOC = "_USER_MENU_DOC";

	/**
	 * BookGrid 书籍列表
	 */
	public String list() {
		QueryFilter filter = new QueryFilter(getRequest());
		List<BookManager> list = this.bookService.getAll(filter);

		Type type = new TypeToken<List<BookManager>>() {
		}.getType();
		StringBuffer buff = new StringBuffer("{success:true,'totalCounts':")
				.append(filter.getPagingBean().getTotalItems()).append(
						",result:");

		Gson gson = new Gson();
		buff.append(gson.toJson(list, type));
		buff.append("}");
		jsonString = buff.toString();

		return "success";
	}

	/**
	 * 保存
	 */
	public String save() {
		if ("".equals(book.getId())) {
			book.setId(null);
		}
		this.bookService.save(book);
		String path = "";
		File uploadPath = new File(this.getRequest()
				.getRealPath(File.separator) + File.separator + "/upload/");
		if (uploadPath.exists()) {
			path = uploadPath.getPath();
		} else {
			uploadPath.mkdirs();// 创建目录结构
			path = uploadPath.getPath();
		}
		if (filePto != null) {
			String c = String.valueOf(System.currentTimeMillis());
			this.upload(path, filePtoFileName, c, book.getPto(),
					filePto.getPath());
			String fileName = c
					+ filePtoFileName.substring(
							filePtoFileName.lastIndexOf("."),
							filePtoFileName.length());
			book.setPto(fileName);
		}
		if (fileElectronic != null) {
			String n = String.valueOf(System.currentTimeMillis());
			this.upload(path, fileElectronicFileName,
					String.valueOf(System.currentTimeMillis()),
					book.getElectronic(), fileElectronic.getPath());
			String fileNamen = n
					+ fileElectronicFileName.substring(
							fileElectronicFileName.lastIndexOf("."),
							fileElectronicFileName.length());
			book.setElectronic(fileNamen);
		}
		this.bookService.save(book);
		Gson gson = new Gson();
		StringBuffer sb = new StringBuffer("{success:true,data:");
		sb.append(gson.toJson(book));
		sb.append("}");
		setJsonString(sb.toString());
		return "success";
	}

	/**
	 * 删除书籍及章节信息
	 */
	public String delete() {
		String[] str = ids.split(",");
		for (int i = 0; i < str.length; i++) {
			BookManager book = this.bookService.get(str[i].trim());
			List list = this.catalogService.search(book.getId());
			if (list != null) {
				for (Iterator iterator = list.iterator(); iterator.hasNext();) {
					BookCatalog object = (BookCatalog) iterator.next();
					this.catalogService.remove(object);
				}
			}
			File uploadPath = new File(this.getRequest().getRealPath(
					File.separator)
					+ File.separator + "/upload/");
			File oldFilePto = new File(uploadPath.getPath() + "\\"
					+ book.getPto());
			if (oldFilePto.exists()) {
				oldFilePto.delete();
			}
			File oldFileElectronic = new File(uploadPath.getPath() + "\\"
					+ book.getElectronic());
			if (oldFileElectronic.exists()) {
				oldFileElectronic.delete();
			}
			this.bookService.remove(book);
		}
		return "success";
	}

	/**
	 * 获取修改信息
	 * 
	 * @return
	 */
	public String get() {
		BookManager book = (BookManager) this.bookService.get(this.id);
		if (book.getAuthor() != null && !"".equals(book.getAuthor())) {
			User user = userService.getById(book.getAuthor());
			book.setAuthorName(user.getName());
		}
		if (book.getType() != null && !"".equals(book.getType())) {
			BookType type = bookTypeService.get(book.getType());
			if (type != null) {
				book.setTypeName(type.getBookCatalogName());
			}
		}
		Gson gson = new Gson();
		StringBuffer sb = new StringBuffer("{success:true,data:");
		sb.append(gson.toJson(book));
		sb.append("}");
		setJsonString(sb.toString());

		return "success";
	}

	public void upload(String path, String fileName, String newFileName,
			String oldFileName, String filePath) {
		FileOutputStream fos = null;
		FileInputStream fis = null;
		try {
			String suffix = fileName.substring(fileName.lastIndexOf("."),
					fileName.length());
			fos = new FileOutputStream(path + File.separator + newFileName
					+ suffix);
			fis = new FileInputStream(filePath);
			byte[] buffer = new byte[10240];
			int len = 0;
			int total = fis.available();
			System.out.println("文件大小为:" + total);
			while ((len = fis.read(buffer)) > 0) {
				fos.write(buffer, 0, len);
				fos.flush();
			}
			File oldFilePto = new File(path + "\\" + oldFileName);
			if (oldFilePto.exists()) {
				oldFilePto.delete();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fis != null) {
					fis.close();
				}
				if (fos != null) {
					fos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
